package org.xurui.bsj.protocol;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.ProtocolSupport;
import org.jetlinks.core.defaults.CompositeProtocolSupport;
import org.jetlinks.core.device.DeviceRegistry;
import org.jetlinks.core.message.codec.DefaultTransport;
import org.jetlinks.core.metadata.ConfigScope;
import org.jetlinks.core.metadata.DefaultConfigMetadata;
import org.jetlinks.core.metadata.DeviceConfigScope;
import org.jetlinks.core.metadata.types.PasswordType;
import org.jetlinks.core.metadata.types.StringType;
import org.jetlinks.core.spi.ProtocolSupportProvider;
import org.jetlinks.core.spi.ServiceContext;
import org.jetlinks.supports.official.JetLinksDeviceMetadataCodec;
import org.xurui.bsj.protocol.codec.TcpMessageCodec;
import org.xurui.bsj.protocol.interceptor.MyDeviceMessageSenderInterceptor;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
 * 博实结设备消息协议
 */
@Slf4j
public class BsjProtocolSupportProvider implements ProtocolSupportProvider {

    /**
     * static uint8_t aes_key[] =
     * {
     *     0x96, 0xB6, 0x71, 0x5E, 0xF5, 0x0F, 0xA4, 0x55,
     *     0x7F, 0x6C, 0xF9, 0x77, 0x17, 0x8E, 0x86, 0xC9
     * };
     *
     * static uint8_t aes_iv[]  =
     * {
     *     0x11, 0xC5, 0x00, 0x74, 0x0B, 0xE4, 0x4D, 0x4E,
     *     0xE5, 0xBD, 0xAE, 0xD0, 0x3C, 0xE7, 0x6F, 0xFF
     * };
     * @param context
     * @return
     */
    @Override
    public Mono<? extends ProtocolSupport> create(ServiceContext context) {
        if (log.isDebugEnabled()) {
            log.debug("初始化博实结设备消息协议");
        }
        DefaultConfigMetadata configMetadata = new DefaultConfigMetadata(
            "博实结产品配置"
            , "")
            .add("iccid", "博实结设备iccid", "不用设置，上线自动设置", new StringType(),DeviceConfigScope.device);
        CompositeProtocolSupport support = new CompositeProtocolSupport();
        // 协议ID
        support.setId("bsj-v1");
        // 协议名称
        support.setName("博实结设备协议-v1");
        // 协议说明
        support.setDescription("博实结设备协议");
        // 物模型编解码，固定为JetLinksDeviceMetadataCodec
        support.setMetadataCodec(new JetLinksDeviceMetadataCodec());
        Optional<DeviceRegistry> registry = context.getService(DeviceRegistry.class);
        MyDeviceMessageSenderInterceptor senderInterceptor = new MyDeviceMessageSenderInterceptor();
        support.addMessageSenderInterceptor(senderInterceptor);



        //TCP消息编解码器
        TcpMessageCodec codec = new TcpMessageCodec(context,senderInterceptor,registry);
        // 两个参数，协议支持和编解码类DemoDeviceMessageCodec中保持一致，第二个参数定义使用的编码解码类
        support.addMessageCodecSupport(DefaultTransport.TCP, () -> Mono.just(codec));
        support.addConfigMetadata(DefaultTransport.TCP,()->Mono.just(configMetadata));
        return Mono.just(support);
    }
}
